<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Crash Verify</title>
  <link rel="stylesheet" href="./css/main.css">
</head>

<body>
  <div id="app">
    <h1>Crash Verify</h1>

    <hr>

    <h2>Input</h2>
    <p>We use the hash of TRON block #43806908: <span class="text-blue-500">{{tronBlock}}</span> as the salt</p>

    <hr>

    <div class="flex flex-col gap-3">
      <input class="border" type="text" placeholder="Game's Hash Value (SHA256)" v-model="hashValue">
      <input class="border" type="text" placeholder="Salt Value (Optional)" v-model="SaltValue">
    </div>


    <h2>Result</h2>
    <h5>Final VerifyResult</h5>
    <pre><code>CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(game_hash), salt)</code></pre>
    <div class="overflow-x-auto">
      <table class="w-full text-center">
        <thead>
          <tr>
            <th class="border p-1">Game's hash</th>
            <th class="border p-1">Bust</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td class="border p-1">{{ hashValue }}</td>
            <td class="border p-1">{{ result }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</body>

<script type="module">
  import './js/tailwindcss.js';
  import { createApp, ref, watch, onMounted, computed } from './js/vue.js';
  import CryptoJS from './js/crypto-js.js';
  import * as helpers from './js/helpers.js';

  function calculateGameResult(hash, salt) {
    // number of most significant bits to use
    const nBits = 52;
    // 1. HMAC_SHA256(message=hash, key=salt)
    if (salt) {
      const hmac = CryptoJS.HmacSHA256(CryptoJS.enc.Hex.parse(hash), salt);
      hash = hmac.toString();
    }
    hash = hash.slice(0, nBits / 4);
    const r = parseInt(hash, 16);
    let X = r / (2 ** nBits);
    X = parseFloat(X.toPrecision(9));
    X = 99 / (1 - X);
    const resultNumber = Math.floor(X);
    return Math.max(1, resultNumber / 100);
  }

  createApp({
    setup() {
      const { h } = helpers.queryParams;
      const tronBlock = computed(() => '00000000029c70bc32d1c9d06ce111871b552abc84cdc50bc196454039363049')
      const hashValue = ref(h ?? '');
      const SaltValue = ref(tronBlock.value);

      // const serverSeedHash = computed(() => CryptoJS.SHA256(CryptoJS.enc.Utf8.parse(serverSeed.value)).toString());
      // const clientNonceHash = computed(() => CryptoJS.HmacSHA256([clientSeed.value, nonceValue.value].join(":"), serverSeed.value).toString());

      const result = computed(() => calculateGameResult(hashValue.value, SaltValue.value));

      return {
        tronBlock,
        hashValue,
        SaltValue,
        // serverSeedHash,
        // clientNonceHash,
        result,
      };
    },
  }).mount('#app');
</script>

</html>